<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>多线程 | SuJin博客</title><meta name="keywords" content="博客，SuJin"><meta name="author" content="SuJin"><meta name="copyright" content="SuJin"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1.volatile可见性 指令重排 不能保证原子性 2.ThreadLocal原理3.HashMap原理-concurrentHashMapjdk1.8虽然加入红黑树但是能转树的概率 百万分之一 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455">
<meta property="og:type" content="article">
<meta property="og:title" content="多线程">
<meta property="og:url" content="https://sujiesujie12456789.gitee.io/2021/03/30/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="SuJin博客">
<meta property="og:description" content="1.volatile可见性 指令重排 不能保证原子性 2.ThreadLocal原理3.HashMap原理-concurrentHashMapjdk1.8虽然加入红黑树但是能转树的概率 百万分之一 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://picsum.photos/id/862/5451/3634">
<meta property="article:published_time" content="2021-03-30T13:05:48.000Z">
<meta property="article:modified_time" content="2022-04-15T12:59:11.046Z">
<meta property="article:author" content="SuJin">
<meta property="article:tag" content="博客，SuJin">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://picsum.photos/id/862/5451/3634"><link rel="shortcut icon" href="http://placekitten.com/350/200"><link rel="canonical" href="https://sujiesujie12456789.gitee.io/2021/03/30/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '多线程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-04-15 20:59:11'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="SuJin博客" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="http://picsum.photos/id/859/1919/1919" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://picsum.photos/id/862/5451/3634')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">SuJin博客</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">多线程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-03-30T13:05:48.000Z" title="发表于 2021-03-30 21:05:48">2021-03-30</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-04-15T12:59:11.046Z" title="更新于 2022-04-15 20:59:11">2022-04-15</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="多线程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="1-volatile"><a href="#1-volatile" class="headerlink" title="1.volatile"></a>1.volatile</h2><p>可见性</p>
<p>指令重排</p>
<p>不能保证原子性</p>
<h2 id="2-ThreadLocal原理"><a href="#2-ThreadLocal原理" class="headerlink" title="2.ThreadLocal原理"></a>2.ThreadLocal原理</h2><h2 id="3-HashMap原理-concurrentHashMap"><a href="#3-HashMap原理-concurrentHashMap" class="headerlink" title="3.HashMap原理-concurrentHashMap"></a>3.HashMap原理-concurrentHashMap</h2><p>jdk1.8虽然加入红黑树但是能转树的概率 百万分之一</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> V <span class="title">put</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> putVal(hash(key), key, value, <span class="keyword">false</span>, <span class="keyword">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line"> 调用真正的put方法之前 会先算出key的<span class="function">hashcode  </span></span><br><span class="line"><span class="function"> </span></span><br><span class="line"><span class="function"> </span></span><br><span class="line"><span class="function">  <span class="keyword">final</span> V <span class="title">putVal</span><span class="params">(<span class="keyword">int</span> hash, K key, V value, <span class="keyword">boolean</span> onlyIfAbsent,</span></span></span><br><span class="line"><span class="params"><span class="function">                   <span class="keyword">boolean</span> evict)</span> </span>&#123;</span><br><span class="line">     	</span><br><span class="line">        Node&lt;K,V&gt;[] tab; Node&lt;K,V&gt; p; <span class="keyword">int</span> n, i;</span><br><span class="line">     <span class="comment">//hashMap默认会创建一个长度为16的node数组</span></span><br><span class="line">        <span class="keyword">if</span> ((tab = table) == <span class="keyword">null</span> || (n = tab.length) == <span class="number">0</span>)</span><br><span class="line">            n = (tab = resize()).length;</span><br><span class="line">     	<span class="comment">//n=16  根据当前key的hash值算出在这个数组的下标</span></span><br><span class="line">        <span class="keyword">if</span> ((p = tab[i = (n - <span class="number">1</span>) &amp; hash]) == <span class="keyword">null</span>)</span><br><span class="line">            tab[i] = newNode(hash, key, value, <span class="keyword">null</span>);<span class="comment">//没有值直接放入 </span></span><br><span class="line">        <span class="keyword">else</span> &#123;<span class="comment">//hash冲突</span></span><br><span class="line">            Node&lt;K,V&gt; e; K k;</span><br><span class="line">            <span class="keyword">if</span> (p.hash == hash &amp;&amp;<span class="comment">//当前放入的key跟原来存在的key相同</span></span><br><span class="line">                ((k = p.key) == key || (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">                e = p;<span class="comment">//替换</span></span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (p <span class="keyword">instanceof</span> TreeNode)</span><br><span class="line">                e = ((TreeNode&lt;K,V&gt;)p).putTreeVal(<span class="keyword">this</span>, tab, hash, key, value);</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> binCount = <span class="number">0</span>; ; ++binCount) &#123;</span><br><span class="line">                    <span class="keyword">if</span> ((e = p.next) == <span class="keyword">null</span>) &#123;</span><br><span class="line">                        p.next = newNode(hash, key, value, <span class="keyword">null</span>);</span><br><span class="line">                        <span class="keyword">if</span> (binCount &gt;= TREEIFY_THRESHOLD - <span class="number">1</span>) <span class="comment">// -1 for 1st</span></span><br><span class="line">                            treeifyBin(tab, hash);</span><br><span class="line">                        <span class="comment">//判断是否树华，数组长度&gt;=64 ,节点长度&gt;=8</span></span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (e.hash == hash &amp;&amp;</span><br><span class="line">                        ((k = e.key) == key || (key != <span class="keyword">null</span> &amp;&amp; key.equals(k))))</span><br><span class="line">                        <span class="keyword">break</span>;</span><br><span class="line">                    p = e;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (e != <span class="keyword">null</span>) &#123; <span class="comment">// existing mapping for key</span></span><br><span class="line">                V oldValue = e.value;</span><br><span class="line">                <span class="keyword">if</span> (!onlyIfAbsent || oldValue == <span class="keyword">null</span>)</span><br><span class="line">                    e.value = value;</span><br><span class="line">                afterNodeAccess(e);</span><br><span class="line">                <span class="keyword">return</span> oldValue;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        ++modCount;</span><br><span class="line">        <span class="keyword">if</span> (++size &gt; threshold)</span><br><span class="line">            resize();<span class="comment">//判断是否扩容</span></span><br><span class="line">        afterNodeInsertion(evict);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">concurrentHashmap--- </span><br><span class="line">    <span class="comment">//两个线程同时插入hashmap 算出hash值都等于3 3这个地方正好没有值 可能会出现覆盖 </span></span><br><span class="line">    <span class="keyword">if</span> (casTabAt(tab, i, <span class="keyword">null</span>,</span><br><span class="line">                             <span class="keyword">new</span> Node&lt;K,V&gt;(hash, key, value, <span class="keyword">null</span>)))</span><br><span class="line">                    <span class="keyword">break</span>; </span><br><span class="line">    <span class="comment">//两个线程同时插入hashmap  算出hash值等于 3这个位置有了，</span></span><br><span class="line"><span class="keyword">synchronized</span></span><br></pre></td></tr></table></figure>

<h2 id="4-synchronized"><a href="#4-synchronized" class="headerlink" title="4.synchronized"></a>4.synchronized</h2><blockquote>
<p>查看字节码文件，</p>
<p><strong>同步方法</strong>会加上acc_synchronized 来隐式实现。运行时<strong>常量池</strong>中方法的 ACC_SYNCHRONIZED 标志[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GnwYgM3q-1639824804688)(线程.assets/ACC_Synchronized.png)]</p>
<p>方法级的同步是隐式，即无需通过字节码指令来控制的，它实现在方法调用和返回操作之中。JVM可以从方法常量池中的方法表结构(method_info Structure) 中的 ACC_SYNCHRONIZED 访问标志区分一个方法是否同步方法。当方法调用时，调用指令将会 检查方法的 ACC_SYNCHRONIZED 访问标志是否被设置，如果设置了，执行线程将先持有monitor， 然后再执行方法</p>
<p><strong>同步代码块</strong>会出现**moniterenter moniterexit 指令,**在正常执行完代码或出现一个异常时，锁释放。</p>
<p><strong>堆空间中</strong>，一个对象的内存布局包含：</p>
<p>对象头：synchronized 的锁对象就在对象头，主要由<strong>Mark Word 和 Class MetaData Address</strong>组成的</p>
<p>Mark Word存储对象的hashCode、锁信息（锁标记位、锁ID）、分代年龄或GC标志等信息。</p>
<img src="线程.assets/image-20210827115215818.png" alt="image-20210827115215818" style="zoom:50%;" />

<p>Class MetaData Address：指针指向对象的类元数据</p>
<p>实例变量：存放类的属性数据信息，包括父类的属性信息，如果是数组的实例部分还包括数组的长度，这部分内存按4字节对齐</p>
<p>对齐填充：由于虚拟机要求对象起始地址必须是8字节的整数倍。填充数据不是必须存在的，仅仅是为了字节对齐</p>
<p>实例对象。<img src="线程.assets/image-20210827095042800.png" alt="image-20210827095042800" style="zoom: 33%;" /></p>
</blockquote>
<p>释放锁：1.同步代码块运行完了，2.同步代码块抛异常</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">javap -verbose xxx.class</span><br><span class="line">同步方法会acc_synchronized</span><br><span class="line">同步代码块会出现 moniterenter moniterexit,完成一个异常----moniterexit</span><br><span class="line"></span><br><span class="line">synchronized(对象)</span><br><span class="line">对象在内存中得布局：</span><br><span class="line"></span><br><span class="line">	对象头</span><br><span class="line"></span><br><span class="line">	实例数据</span><br><span class="line"></span><br><span class="line">	对齐填充</span><br><span class="line">java对象头:</span><br><span class="line">new Student()----student.class</span><br><span class="line">class metadata address:指向class对象的指针，虚拟机可以确定该对象时哪个class的实例</span><br><span class="line">mark word：对象的信息，标志位等，实现锁的关键  id属性</span><br><span class="line">		对象的信息：	hashcode，分代年龄:gc 垃圾回收</span><br><span class="line">		锁类型:</span><br><span class="line">		锁标志位: 01(无) 00(轻量级) 10（重量级）  轻量级 重量级不同的 </span><br><span class="line">		还会记录，当前持有该锁的线程是谁</span><br><span class="line">只靠标记是不行：mointer监视器---来完成加锁放锁 也叫管程</span><br><span class="line">ObjectMointer父类 c++实现的，每一个对象都一定会有一个moniter，出现的时间：伴随着对象的出生而出生，第一次去拿对象锁的时候出生,moniterenter  moniterexit</span><br><span class="line">重要属性：</span><br><span class="line"></span><br><span class="line">	waitset:保存抢到该锁以后调用wait方法的线程</span><br><span class="line"></span><br><span class="line">	entrylist：记录没有抢到锁的线程。多个线程  5个线程来抢锁，某个线程抢到锁，对象mark word id=当前线程的id</span><br><span class="line"></span><br><span class="line">	owner：抢到锁的线程     如果释放锁，owner置空</span><br><span class="line"></span><br><span class="line">	count:+1     -1</span><br><span class="line">A线程来了 把owner---改为A count+1 ----B线程来了，A线程还在执行 B进入entrylist等待----A线程执行wait方法，进入waitset里面</span><br><span class="line"></span><br><span class="line">jdk6以前，lock比synchronized效率高很多，mutex lock效率低</span><br><span class="line">    synchronized属于重量级锁，效率低下，因为监视器锁（monitor）是依赖于底层的操作系统的Mutex Lock来实现的，而操作系统实现线程之间的切换时需要从用户态转换到核心态，这个状态之间的转换需要相对比较长的时间，时间成本相对较高</span><br><span class="line">    </span><br><span class="line">jdk6以后做了优化，</span><br><span class="line">B线程去拿锁 拿不到---转等待状态----B想运行又要转回来--浪费了效率</span><br><span class="line">    </span><br><span class="line">    自旋：多数时候，拿锁就一哈哈儿，如果去切换得不偿失，就可以让其它线程while(true)不释放cpu还更快</span><br><span class="line"></span><br><span class="line">	但是锁的时间长，自旋就长，就更消耗了用户可以更改，参数可以不用管</span><br><span class="line">	就有了**自适应自旋锁**：由前一次，在同一个锁上自旋时间及锁的持有时间，可以自动调整自旋时间，甚至可以不自旋</span><br><span class="line"></span><br><span class="line">**锁消除**</span><br><span class="line"></span><br><span class="line">	stringbuffer 自动消除</span><br><span class="line"></span><br><span class="line">​```java</span><br><span class="line">//方法属于线程栈  天生线程安全 内部的东西都是安全的 没必要加锁</span><br><span class="line">    //jvm 会把锁自动消除：锁消除</span><br><span class="line">    public void test()&#123;</span><br><span class="line">        StringBuffer stringBuffer = new StringBuffer();</span><br><span class="line">        stringBuffer.append(&quot;abc&quot;);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p><strong>锁粗化：</strong></p>
<pre><code>    循环多次stringbuffer 每次调用方法都会加锁
</code></pre>
<p>StringBuffer stringBuffer = new StringBuffer();<br>    public void test(){<br>    synchronized(){//锁粗化<br>       while(1000次)<br>        stringBuffer.append(“abc”);<br>        }<br>    }<br>会在栈里面复制一份moniter的信息，对象头<br>对象头会有一个指针</p>
<p>无锁、偏向锁、轻量级锁、重量级锁<br>偏向锁:只有一个线程 抢锁，本来抢锁需要很多认证，改一些标记，先把这些标记标记为这个线程，减少加锁的流程<br>（就偏向于他了 mark word(堆中)的id=当前线程的thread id）<br>轻量级锁：AB交替执行，偏向锁—-轻量级锁<br>轻量级锁：很多线程大家没有规律抢 —-重量级锁</p>
<p>锁的释放依赖moniter：jmm内存模型，1.把数据同步，高速缓冲(栈的内存) 比如读取student对象 修改student对象 写入student对象到堆，另外把其它栈里面有这个对象的全部要求重新读取(可见性) 2.修改对象头信息，锁标志，id，指针</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">https://www.cnblogs.com/wuzhenzhao/p/10250801.html</span><br><span class="line"></span><br><span class="line">https://blog.csdn.net/javazejian/article/details/72828483</span><br><span class="line"></span><br><span class="line">https://blog.csdn.net/scdn_cp/article/details/86491792</span><br><span class="line"></span><br><span class="line">## 5.安全集合</span><br><span class="line"></span><br><span class="line">vector:所有的方法都加锁，效率较低，不建议使用</span><br><span class="line"></span><br><span class="line">读读的问题，</span><br><span class="line"></span><br><span class="line">CopyOnWriteArrayList/CopyOnWriteArraySet:写时复制</span><br><span class="line"></span><br><span class="line">读写分离的思想</span><br><span class="line"></span><br><span class="line">CopyOnWriteArrayList 仅适用于写操作非常少的场景，而且能够容忍读写的短暂不一致</span><br><span class="line"></span><br><span class="line">内存占用问题　数据一致性问题</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">写时复制：复制的那一份去修改，修改完了 替换原来</span><br><span class="line"></span><br><span class="line">1.空间浪费</span><br><span class="line"></span><br><span class="line">2.数据不一致</span><br><span class="line"></span><br><span class="line">适用场景 读多写少</span><br><span class="line"></span><br><span class="line">## 6.死锁</span><br><span class="line"></span><br><span class="line">​```java</span><br><span class="line">package cn.cdqf.dead;</span><br><span class="line"></span><br><span class="line">public class MyDeadLock implements Runnable&#123;</span><br><span class="line">    private MyLock myLock1 = new MyLock();</span><br><span class="line">    private MyLock myLock2 = new MyLock();</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        synchronized (myLock1)&#123;</span><br><span class="line">            //Thread-1获得了myLock1</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+&quot;获得了myLock1&quot;);</span><br><span class="line">            synchronized (myLock2)&#123;</span><br><span class="line">                System.out.println(Thread.currentThread().getName()+&quot;获得了myLock2&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        synchronized (myLock2)&#123;</span><br><span class="line">            //Thread-0获得了myLock2</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+&quot;获得了myLock2&quot;);</span><br><span class="line">            synchronized (myLock1)&#123;</span><br><span class="line">                System.out.println(Thread.currentThread().getName()+&quot;获得了myLock1&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        MyDeadLock myDeadLock = new MyDeadLock();</span><br><span class="line">        new Thread(myDeadLock).start();</span><br><span class="line">        new Thread(myDeadLock).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class MyLock&#123;&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>线程之间互相等待对方释放锁，就是死锁</p>
<p>编号解死锁：对多把锁 按从小到大排序，每个要用多锁的地方，都先锁小的，再锁大的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.cdqf.deadlock;</span><br><span class="line"><span class="comment">//一般syn里面锁芯不用String 因为String会放在字符串常量池，所以容易出现多个地方锁相同</span></span><br><span class="line"><span class="comment">//也少用Integer -128---127被缓存了的 是同一个对象</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DeadLockTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> MyLock myLock1 = <span class="keyword">new</span> MyLock(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">private</span> MyLock myLock2 = <span class="keyword">new</span> MyLock(<span class="number">2</span>);</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test1</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//一个地方 A在前B在后 另外一个地方B在前 A在后</span></span><br><span class="line">        <span class="comment">//现在给锁编号 那么永远小的在前</span></span><br><span class="line">        <span class="keyword">if</span>(myLock1.getI()&lt;myLock2.getI())&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (myLock1)&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">300</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">synchronized</span> (myLock2)&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (myLock2)&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">300</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">synchronized</span> (myLock1)&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test2</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(myLock1.getI()&lt;myLock2.getI())&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (myLock1)&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">300</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">synchronized</span> (myLock2)&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (myLock2)&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">300</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">synchronized</span> (myLock1)&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="7-wait-notify-notifyall"><a href="#7-wait-notify-notifyall" class="headerlink" title="7.wait/notify/notifyall"></a>7.wait/notify/notifyall</h2><p>wait():等待，释放锁 来源于 object的 notify——waitset</p>
<p>调用wait方法 这个线程会进入 moniter waitset()———依赖对象  syn(A)</p>
<p>wait notify notifyall 都需要在同步代码块里面运行——-是同步那个锁芯调用的</p>
<p>Sys….(A){}:A对象锁代码块里面的notify只能叫醒A对象代码里面wait</p>
<p>1.同步代码块里面运行:java.lang.IllegalMonitorStateException：</p>
<p>2.Object方法：wait/notify/notifyall</p>
<p>3.notify随机叫醒一个wait</p>
<p>4.notifyAll当前对象所有的wait()</p>
<p>A  B{A.join}  B线程需要等到A线程执行结束才继续执行</p>
<p>wait/notify必须要同步代码块中使用</p>
<p>当前所对象的包含的代码中没有wait的线程，没法叫</p>
<p>当前锁对象中的notify/notifyAll只能叫醒，当前锁对象包含中的wait()</p>
<p>wait与notify与notifyAll锁对象是谁就必须用锁对象来调用方法，不然会出现IllegalMonitorStateException</p>
<p>这三个方法都是在Object类，所以每一个对象都有这三个方法</p>
<p>一般都用notifyAll：叫醒当前锁对象中所有的wait方法</p>
<p>notify：随机叫一个</p>
<p>被wait以后会释放锁</p>
<h2 id="8-线程提高效率"><a href="#8-线程提高效率" class="headerlink" title="8.线程提高效率"></a>8.线程提高效率</h2><p>多核—-多线程肯定能提高效率</p>
<p>即使在一个核里面2个也可以提高效率：</p>
<p>CPU密集型：项目是大量的运算，  </p>
<p>IO密集型：大部分io操作  </p>
<p>混合型：io/cpu混合的   </p>
<p>计算机两大块，某一个块是运行cpu的，另外一个ram运行磁盘–内核</p>
<h2 id="9-线程池"><a href="#9-线程池" class="headerlink" title="9.线程池"></a>9.线程池</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor threadPoolExecutor =</span><br><span class="line">           <span class="keyword">new</span> ThreadPoolExecutor(</span><br><span class="line">                   <span class="comment">//核心线程数:线程创建的时候就初始化这么多个线程：</span></span><br><span class="line">                   <span class="comment">//默认核心线程不回收 但是 threadPoolExecutor.allowCoreThreadTimeOut(true);回收时间跟非核心相同</span></span><br><span class="line">                   <span class="comment">// 最大线程数:20-10忙不过来的时候 还可以创建10个线程</span></span><br><span class="line">                   <span class="number">10</span>,<span class="number">20</span>,</span><br><span class="line">                   <span class="comment">//非核心线程数 回收时间:非核心线程 空闲超过这个时间那么就被回收</span></span><br><span class="line">                   <span class="number">10000</span>,</span><br><span class="line">                   <span class="comment">//单位</span></span><br><span class="line">                   TimeUnit.MILLISECONDS,</span><br><span class="line">                   <span class="comment">//任务队列</span></span><br><span class="line">                   <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="number">50</span>)</span><br><span class="line">                   <span class="comment">//拒绝策略:线程池都忙不过来的时候，可以适当选择拒绝</span></span><br><span class="line">                   <span class="comment">/**</span></span><br><span class="line"><span class="comment">                    *  ThreadPoolExecutor.AbortPolicy();//默认，队列满了丢任务抛出异常</span></span><br><span class="line"><span class="comment">                    * ThreadPoolExecutor.DiscardPolicy();//队列满了丢任务不异常:菲律宾真人荷官</span></span><br><span class="line"><span class="comment">                    * ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删，之后再尝试加入队列</span></span><br><span class="line"><span class="comment">                    * ThreadPoolExecutor.CallerRunsPolicy();//如果添加到线程池失败，那么主线程会自己去执行该任务</span></span><br><span class="line"><span class="comment">                    */</span></span><br><span class="line">           , <span class="keyword">new</span> ThreadPoolExecutor.AbortPolicy());</span><br><span class="line">           <span class="comment">//来了任务 核心线程先上  放入任务队列 忙不过来了  创建非核心线程  还有任务  任务队列满了就拒绝策略</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">offer(E e): 将给定的元素设置到队列中，如果设置成功返回<span class="keyword">true</span>, 否则返回<span class="keyword">false</span>. e的值不能为空，否则抛出空指针异常。</span><br><span class="line"></span><br><span class="line">offer(E e, <span class="keyword">long</span> timeout, TimeUnit unit): 将给定元素在给定的时间内设置到队列中，如果设置成功返回<span class="keyword">true</span>, 否则返回<span class="keyword">false</span>.</span><br><span class="line"></span><br><span class="line">add(E e): 将给定元素设置到队列中，如果设置成功返回<span class="keyword">true</span>, 否则抛出异常。如果是往限定了长度的队列中设置值，推荐使用offer()方法。</span><br><span class="line"></span><br><span class="line">put(E e): 将元素设置到队列中，如果队列中没有多余的空间，该方法会一直阻塞，直到队列中有多余的空间。</span><br><span class="line"></span><br><span class="line">take(): 从队列中获取值，如果队列中没有值，线程会一直阻塞，直到队列中有值，并且该方法取得了该值。</span><br><span class="line"></span><br><span class="line">poll(<span class="keyword">long</span> timeout, TimeUnit unit): 在给定的时间里，从队列中获取值，如果没有取到会抛出异常。</span><br><span class="line"></span><br><span class="line">remainingCapacity()：获取队列中剩余的空间。</span><br><span class="line"></span><br><span class="line">remove(Object o): 从队列中移除指定的值。</span><br><span class="line"></span><br><span class="line">contains(Object o): 判断队列中是否拥有该值。</span><br><span class="line"></span><br><span class="line">drainTo(Collection c): 将队列中值，全部移除，并发设置到给定的集合中。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">https:<span class="comment">//blog.csdn.net/weixin_37598682/article/details/79895769</span></span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">n核的个数</span><br><span class="line"></span><br><span class="line">n+1：cpu密集型，尽量一个cpu去抛一个线程，减少上下文切换</span><br><span class="line"></span><br><span class="line">2n：io密集型 有线程去做io的时候 另外的线程让cpu利用起来</span><br><span class="line"></span><br><span class="line">混合型：</span><br><span class="line">n*u*(1+WT/ST)</span><br><span class="line">u:目标cpu利用率</span><br><span class="line">wt：线程等待时间</span><br><span class="line">st：线程运行时间</span><br><span class="line"></span><br><span class="line">终端：jvisualvm --profiler--项目---</span><br><span class="line">自用st</span><br><span class="line">总-st=wt</span><br><span class="line"></span><br><span class="line">调优</span><br><span class="line">javacodegeeks.com/2012/03/threading-stories-about-robust-thread.html</span><br></pre></td></tr></table></figure>

<h2 id="10-AQS"><a href="#10-AQS" class="headerlink" title="10.AQS"></a>10.AQS</h2><p>AQS的源码我简单看了一下，没怎么看懂</p>
<p>我自己的理解就是，aqs是一套jdk帮我们实现了类似于加锁解锁，线程协作，获得许可，释放许可等基本功能的工具体系类，正是基于这些基础的工具，实现大量的比如信号量，ReentrantLock,CyclicBarrier方便开发人员并发类</p>
<h2 id="11-syn与lock区别"><a href="#11-syn与lock区别" class="headerlink" title="11.syn与lock区别"></a>11.syn与lock区别</h2><p>获得锁的条件，释放锁，是否公平，原理。。。。。</p>
<h2 id="12-线程在哪儿用的"><a href="#12-线程在哪儿用的" class="headerlink" title="12.线程在哪儿用的"></a>12.线程在哪儿用的</h2><p>项目里面哪个场景</p>
<h2 id="13-cas"><a href="#13-cas" class="headerlink" title="13.cas"></a>13.cas</h2><p>Compare and Swap：比较并交换 cpu保证的</p>
<p>V A B</p>
<p>V是i的值  1</p>
<p>A现在读取i的值  1</p>
<p>B 改变后的值  2</p>
<p>concurrentHashMap:</p>
<p>AtomicInteger—-unsafe compareAndSwapInt</p>
<p>2个操作</p>
<p>比较并交换—比较是否是原来的值  才交换(原子性) 在java里面没有原子，汇编语言 一个指令</p>
<p>ABA问题:AtomicStampedReference—jdk提供的就可以</p>
<h2 id="14springboot的线程池"><a href="#14springboot的线程池" class="headerlink" title="14springboot的线程池"></a>14springboot的线程池</h2><p>普通配置线程池 @async</p>
<p>定时任务 单独的线程池</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">SuJin</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://sujiesujie12456789.gitee.io/2021/03/30/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">https://sujiesujie12456789.gitee.io/2021/03/30/%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://sujiesujie12456789.gitee.io" target="_blank">SuJin博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://picsum.photos/id/862/5451/3634" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/2021/04/30/Spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/"><img class="prev-cover" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring学习笔记</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="http://picsum.photos/id/859/1919/1919" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">SuJin</div><div class="author-info__description">SuJin的博客，欢迎访问</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="card-info-data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">0</div></a></div><div class="card-info-data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/sujin1125" target="_blank" title="Gitee"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:sujin_a@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://sujin1125.gitee.io/" target="_blank" title="博客"><i class="fab fa-algolia"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-volatile"><span class="toc-number">1.</span> <span class="toc-text">1.volatile</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-ThreadLocal%E5%8E%9F%E7%90%86"><span class="toc-number">2.</span> <span class="toc-text">2.ThreadLocal原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-HashMap%E5%8E%9F%E7%90%86-concurrentHashMap"><span class="toc-number">3.</span> <span class="toc-text">3.HashMap原理-concurrentHashMap</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-synchronized"><span class="toc-number">4.</span> <span class="toc-text">4.synchronized</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-wait-notify-notifyall"><span class="toc-number">5.</span> <span class="toc-text">7.wait&#x2F;notify&#x2F;notifyall</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#8-%E7%BA%BF%E7%A8%8B%E6%8F%90%E9%AB%98%E6%95%88%E7%8E%87"><span class="toc-number">6.</span> <span class="toc-text">8.线程提高效率</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#9-%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="toc-number">7.</span> <span class="toc-text">9.线程池</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#10-AQS"><span class="toc-number">8.</span> <span class="toc-text">10.AQS</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#11-syn%E4%B8%8Elock%E5%8C%BA%E5%88%AB"><span class="toc-number">9.</span> <span class="toc-text">11.syn与lock区别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#12-%E7%BA%BF%E7%A8%8B%E5%9C%A8%E5%93%AA%E5%84%BF%E7%94%A8%E7%9A%84"><span class="toc-number">10.</span> <span class="toc-text">12.线程在哪儿用的</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#13-cas"><span class="toc-number">11.</span> <span class="toc-text">13.cas</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#14springboot%E7%9A%84%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="toc-number">12.</span> <span class="toc-text">14springboot的线程池</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2022/04/15/java%E7%AC%94%E8%AF%95%E9%A2%98%E6%80%BB%E7%BB%93/" title="“java笔试题总结”"><img src="https://picsum.photos/id/862/5451/3634" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="“java笔试题总结”"/></a><div class="content"><a class="title" href="/2022/04/15/java%E7%AC%94%E8%AF%95%E9%A2%98%E6%80%BB%E7%BB%93/" title="“java笔试题总结”">“java笔试题总结”</a><time datetime="2022-04-15T07:53:41.000Z" title="发表于 2022-04-15 15:53:41">2022-04-15</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/03/30/Nginx/" title="Nginx"><img src="https://picsum.photos/id/862/5451/3634" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Nginx"/></a><div class="content"><a class="title" href="/2022/03/30/Nginx/" title="Nginx">Nginx</a><time datetime="2022-03-30T14:01:07.000Z" title="发表于 2022-03-30 22:01:07">2022-03-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/03/30/SpringMVC%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="SpringMVC学习笔记"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="SpringMVC学习笔记"/></a><div class="content"><a class="title" href="/2022/03/30/SpringMVC%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="SpringMVC学习笔记">SpringMVC学习笔记</a><time datetime="2022-03-30T13:35:27.000Z" title="发表于 2022-03-30 21:35:27">2022-03-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2022/03/30/MyBatis/" title="MyBatis学习"><img src="https://picsum.photos/id/862/5451/3634" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MyBatis学习"/></a><div class="content"><a class="title" href="/2022/03/30/MyBatis/" title="MyBatis学习">MyBatis学习</a><time datetime="2022-03-30T13:08:22.000Z" title="发表于 2022-03-30 21:08:22">2022-03-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/12/18/redis/" title="redis笔记"><img src="https://picsum.photos/id/862/5451/3634" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="redis笔记"/></a><div class="content"><a class="title" href="/2021/12/18/redis/" title="redis笔记">redis笔记</a><time datetime="2021-12-18T12:47:07.000Z" title="发表于 2021-12-18 20:47:07">2021-12-18</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By SuJin</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>